<?php

namespace App\Http\Controllers\H5;

use App\Common\SDK\Facade\BaiDu;
use App\Common\Utils\Helper;
use App\Http\Controllers\Controller;
use App\Models\Client;
use Illuminate\Cache\RateLimiter;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

class ClientController extends Controller
{
    public function store(Request $request)
    {
        validator($request->all(), [
            'phone' => 'required',
            'province' => 'required',
            'city' => 'required',
            'area' => 'required',
            'address' => 'required',
            'name' => 'required|max:32'
        ], [
            'phone.required' => '手机号不能为空',
            'province.required' => '请选择省份',
            'city.required' => '请选择市',
            'area.required' => '请选择区',
            'address.required' => '详细地址不能为空',
            'name.max' => '客户名称过长',
            'name.required' => '客户名称不能为空'
        ])->validate();

        $clientInfo = $request->only(['name', 'phone', 'province', 'city', 'area', 'address']);
        $clientInfo['agent_id'] = $this->user->getKey();
        $client = Client::query()->firstOrCreate($clientInfo, $clientInfo);

        return $this->response->created(null, $client);
    }

    public function list(Request $request)
    {
        return $this->response->array(
            Helper::dealWithNotCompatibleSimplePaginate(
                Client::query()
                    ->with(['province', 'city', 'area'])
                    ->where('agent_id', $this->user->getKey())
                    ->when($request->get('search_name'), function (Builder $builder, $searchName) {
                        $builder->where(function (Builder $builder) use ($searchName) {
                            $isPhoneSearch = (mb_strlen($searchName) === 11) && is_numeric($searchName);

                            $builder
                                ->where('phone', $isPhoneSearch ? '=' : 'like', $isPhoneSearch ? $searchName : "%$searchName%")
                                ->orWhere('name', 'like', "%$searchName%");
                        });
                    })
                    ->simplePaginate()
            )
        );
    }

    public function update(Request $request, $id)
    {
        validator($request->all(), [
            'phone' => 'required',
            'province' => 'required',
            'city' => 'required',
            'area' => 'required',
            'address' => 'required',
            'name' => 'required|max:16'
        ], [
            'phone.required' => '手机号不能为空',
            'province.required' => '请选择省份',
            'city.required' => '请选择市',
            'area.required' => '请选择区',
            'address.required' => '详细地址不能为空',
            'name.max' => '客户名称过长',
            'name.required' => '客户名称不能为空'
        ])->validate();

        $client = Client::query()
            ->where([
                'id' => $id,
                'agent_id' => $this->user->getKey()
            ])
            ->firstOrFail();
        $client->update($request->only(['name', 'phone', 'province', 'city', 'area', 'address']));

        return $this->response->created(null, $client);
    }

    public function destory($id)
    {
        Client::query()
            ->where([
                'id' => $id,
                'agent_id' => $this->user->getKey()
            ])
            ->delete();

        return $this->response->noContent();
    }

    /**
     * 百度地区识别
     * @param Request $request
     * @return mixed
     */
    public function baiduNlpAddress(Request $request)
    {
        $rateLimiter = app()->make(RateLimiter::class);
        $rateLimiterKey = sprintf('agent_%d_client_address_nlp', $this->user->getKey());
        if ($rateLimiter->tooManyAttempts($rateLimiterKey, 1)) {
            $this->response->errorForbidden('操作的太快啦,如果识别的还有问题,请手动校准下吧');
        }
        $rateLimiter->hit($rateLimiterKey, 10); // 限流 十秒内

        return $this->response->array(BaiDu::address($request->get('address', '')));
    }
}
